<?php
include_once "otamu_config.php";

db_connect();
session_start();

//Checks if there is a login session

if(isset($_SESSION['ID_my_site'])) { 	//if there is, it logs you in and directes you to the members page
 
	$username = $_SESSION['ID_my_site'];
	$pass = $_SESSION['Key_my_site'];
	
	$check = pg_query("SELECT * FROM users WHERE username = '$username'");

	while($info = pg_fetch_array( $check )) {
		if ($pass != $info['passwd']) {
			
		}
		else
		{
			//header("Location: ?");

		}

	}
	if (!isset($_REQUEST['act'])) 
		$act = 'letthemin';

}
else {
	define("_VIEWPATH_",dirname(__FILE__)."/auth/views/");
	if ( !isset( $_REQUEST['act'] ) ) 
		$act = 'login';
	else
		//$act = $_REQUEST['act'];
		header("Location: index.php");
}

		
switch ($act) {

	case "login" :
		//include _VIEWPATH_."$act.php";exit;
		include _VIEWPATH_."login_layout.php";exit;
		break;

	case "authenticate" :
		if(!$_REQUEST['username'] | !$_REQUEST['pass']) {
			exitError('You did not fill in a required field.');
		}
		// checks it against the database
		$_POST['pass'] = stripslashes($_POST['pass']);
		$_POST['pass'] = md5($_POST['pass']);

		$check = pg_query("SELECT * FROM users WHERE username = '".$_POST['username']."' AND passwd = '".$_POST['pass']."'");

		$check2 = pg_num_rows($check);
		if ($check2 == 0) {
			exitError("Username or password not matched.");
		}
		else {
			$_POST['username'] = stripslashes($_REQUEST['username']);
	
			session_register(ID_my_site);
			session_register(Key_my_site);

			$_SESSION['ID_my_site']=$_REQUEST['username'];
			$_SESSION['Key_my_site']=$_REQUEST['pass'];
			
			//check if user is school user with kod_institusi=login
			$dat = pg_fetch_object($check);
			session_register(ACCESS_LEVEL);
			$_SESSION['ACCESS_LEVEL'] = $dat->level;

			if ($dat->level == '1') {
				session_register(KOD_NEGERI);
				$_SESSION['KOD_NEGERI']  = $dat->kod_negeri;
				
			}
			
			//roles
			session_register(user_roles);
			session_register(current_role);
			
			$sql = "select user_id,username,role_id,r.name as role_name from users as u 
			        INNER JOIN users_roles as ur ON ur.user_id=u.id 
					INNER JOIN roles as r ON r.id=ur.role_id
					WHERE username='$username'";
			$r = pg_query($sql);
			if (pg_numrows($r)==0) {
				$_SESSION['current_role'] = 'admin';
			}
			elseif (pg_numrows($r)==1) {
				$d = pg_fetch_object($r,0);
				$_SESSION['current_role'] = strtolower($d->role_name);
			}
			else {
				$_SESSION['current_role'] = '';
				$arr = array();
				while ($d = pg_fetch_object($r)) {
					$arr[] = strtolower($d->role_name);
				}
				$_SESSION['user_roles'] = $arr;
			}
						
			header ("Location: index.php");
		}
		break;

	case "logout" :
		session_start();
		session_unregister('ID_my_site');
		session_unregister('KEY_my_site');

		session_destroy();
		
		header ("Location: index.php");
		break;

	case "new_user":
		$roles  = pg_query("SELECT * FROM roles ORDER BY name");
		
		define("_VIEWPATH_",dirname(__FILE__)."/auth/views/");
		include _VIEWPATH_."otamu_layout.php";
		break;

	case "create_user":
		$passwd = md5($_REQUEST['passwd']);
		$username = $_REQUEST['username'];
		$sql = "INSERT INTO users(username,passwd) VALUES('$username','$passwd')";
		if ($res = pg_query($sql)) {
			$r = pg_query("SELECT last_value FROM pengguna_id_seq");
			$d = pg_fetch_array($r,0);
			$user_id = $d['last_value'];
			$is_create_user_success = true;
		}
		if (!$is_create_user_success) {
			$_SESSION[''] = 'Error';
			header("Location: ?act=user_list");exit;
		}else{
			$ids = $_REQUEST['role_ids'];
			for ($i=0;$i<sizeof($ids);$i++) {
				$sql = "INSERT INTO users_roles(user_id,role_id) VALUES($user_id,$ids[$i])";
				pg_query($sql);
			}
			$_SESSION['flash'] = 'Data Pengguna berjaya disimpan';
		}
		
		header("Location: ?act=user_list");
		break;

	case "edit_user":
		$user_id = $_REQUEST['id'];
		
		$r = pg_query("SELECT * FROM users where id=$user_id");
		$d = pg_fetch_array($r,0);
		$edit_username = $d['username'];
		
		//find this user roles
		$r = pg_query("SELECT * FROM users_roles WHERE user_id=$user_id");
		$edit_roles = array();
		while ($d = pg_fetch_array($r)) {
			$edit_roles[] = $d['role_id'];
		}

		//find all roles
		$roles = pg_query("SELECT * FROM roles");
		define("_VIEWPATH_",dirname(__FILE__)."/auth/views/");
		include _VIEWPATH_."otamu_layout.php";
		
		break;
	
	case "update_user":
		$user_id = $_REQUEST['id'];
		$ids = $_REQUEST['role_ids'];
		pg_query("DELETE FROM users_roles WHERE user_id=$user_id");
		for ($i=0;$i<sizeof($ids);$i++) {
			$sql = "INSERT INTO users_roles(user_id,role_id) VALUES($user_id,$ids[$i])";
			if (pg_query($sql)) {
				$_SESSION['flash'] = 'Data Pengguna berjaya disimpan';
			} else{
				$_SESSION['flash'] = 'Error';
			}
		}
		header("Location: ?act=user_list");
		break;
		
	case "destroy_user":
		$user_id = $_REQUEST['id'];
		pg_query("DELETE FROM users_roles WHERE user_id=$user_id");
		pg_query("DELETE FROM users WHERE id = $user_id");
		header("Location: ?act=user_list");
		break;

	case "user_list":
		$exclude_admin = "AND u.username!='admin'";
		$sql = "SELECT * FROM users WHERE username!='admin' ORDER by username";
		if (isset($_REQUEST['role'])) {
			$sql = "SELECT * FROM users as u INNER JOIN users_roles as ur ON ur.user_id=u.id ".
			       " WHERE role_id=". $_REQUEST['role'] . 
				   " $exclude_admin " .
				   "  ORDER by username";
		}
		$users = pg_query($sql);
		
		$alls = pg_query("SELECT * FROM users WHERE username != 'admin'");
		$wardens = pg_query("SELECT * FROM users as u INNER JOIN users_roles as ur ON ur.user_id=u.id ".
			       " WHERE role_id=2 AND  id!=1 $exclude_admin ORDER by username");
		$heps = pg_query("SELECT * FROM users as u INNER JOIN users_roles as ur ON ur.user_id=u.id ".
			       " WHERE role_id=3 AND  id!=1 $exclude_admin ORDER by username");
		$guards = pg_query("SELECT * FROM users as u INNER JOIN users_roles as ur ON ur.user_id=u.id ".
			       " WHERE role_id=4 AND  id!=1 $exclude_admin ORDER by username");
				
		define("_VIEWPATH_",dirname(__FILE__)."/auth/views/");
		include _VIEWPATH_."otamu_layout.php";
		break;

	case "role_list":
		$roles = pg_query("SELECT * FROM roles ORDER BY id");	
		define("_VIEWPATH_",dirname(__FILE__)."/auth/views/");
		include _VIEWPATH_."otamu_layout.php";
	
		break;		
	case "new_role":
		define("_VIEWPATH_",dirname(__FILE__)."/auth/views/");
		include _VIEWPATH_."otamu_layout.php";
	
		break;		

	case "edit_role":
		$role_id = $_REQUEST['id'];
		$r = pg_query("SELECT * FROM roles where id=$role_id");	
		$d = pg_fetch_array($r,0);
		$role_id = $d['id'];
		$role_name = $d['name'];
		$role_description = $d['description'];
		define("_VIEWPATH_",dirname(__FILE__)."/auth/views/");
		include _VIEWPATH_."otamu_layout.php";
		break;

	case "create_role":
		$role_name = $_REQUEST['name'];
		$role_description = $_REQUEST['description'];
		if ($r = pg_query("INSERT INTO roles(name,description,omnipotent,system_role) ".
		         " VALUES('$role_name','$role_description','t','t')")) {
			
			$_SESSION['flash'] = 'Peranan berjaya disimpan';		 
		}else {
			$_SESSION['flash'] = 'Error';
		}

		header("Location: ?act=role_list");
	
		break;		
		
	case "update_role":
		$role_id = $_REQUEST['id'];
		$role_name = $_REQUEST['name'];
		$role_description = $_REQUEST['description'];
		if ($r = pg_query("UPDATE roles set name='$role_name',description='$role_description' WHERE id=$role_id") ) {
			$_SESSION['flash'] = 'Peranan berjaya disimpan';
		}else{
			$_SESSION['flash'] = 'Error';
		}
		header("Location: ?act=role_list");
	
		break;		
	case "destroy_role":
		error_reporting(0);
		$role_id = $_REQUEST['id'];
		if ($r = pg_query("DELETE FROM roles WHERE id=$role_id")) {
			$_SESSION['flash'] = 'Peranan berjaya dipadam';
		}else{
			$_SESSION['flash'] = 'Error: \nMasih Ada Pengguna Untuk Peranan Ini.\nSila Padam Pengguna Untuk Peranan Ini Dahulu! ';
		}
		header("Location: ?act=role_list");
	
		break;		

	case "edit_role_menu":
		//find the role
		$role_id = $_REQUEST['role_id'];
		$r = pg_query("SELECT * FROM roles where id=$role_id");	
		$the_role = pg_fetch_object($r,0);

		//find menus belongs to the role	
		$rm = pg_query("SELECT * FROM role_menus WHERE role_name ilike '$the_role->name'");
		if (pg_numrows($rm)==1) {
			$role_menus = pg_fetch_object($rm,0);
			$role_menus = $role_menus->menus;
		}else{
			$role_menus = '';
		}
		$role_menus = preg_replace("/{|}/","",$role_menus);
		$role_menus = split(",",$role_menus);
		//print_r($role_menus);//exit;

		//find all menus
		$menus = pg_query("SELECT * FROM menus ORDER BY sort");

		//render		
		define("_VIEWPATH_",dirname(__FILE__)."/auth/views/");
		include _VIEWPATH_."otamu_layout.php";

		break;

	case "save_role_menu":
		$role_id = $_REQUEST['role_id'];
		$r = pg_query("SELECT * FROM roles where id=$role_id");	
		$the_role = pg_fetch_object($r,0);

		$joined_menus = "{" . join(",",$_REQUEST['menu_ids']) . "}";
		
		//check if already exist
		$role_name = strtolower($the_role->name);
		$role_menu_sql = "SELECT * FROM role_menus WHERE role_name='$role_name'";
		$role_menu_res = pg_query($role_menu_sql);
		if (pg_numrows($role_menu_res) == 1) {
			$save_sql = "UPDATE role_menus SET menus='$joined_menus' where role_name='$role_name'";
		}else{
			$save_sql = "INSERT INTO role_menus(role_name,menus) VALUES('$role_name','$joined_menus')";
		}
		//echo $save_sql;exit;
		
		//$sql = "INSERT INTO role_menus(role_name,menus) VALUES('$the_role->name','$joined_menus')";
		if (pg_query($save_sql)) {
			$_SESSION['flash'] = "Menu untuk peranan $the_role->name berjaya disimpan";
			header("Location: pengguna.php?act=role_list");
		} else {
			$_SESSION['flash'] = 'Error.';
			$act = 'edit_role_menu';
		}
		break;

	default :
							
		//echo "OKKK";
}

			//workaround, to avoid session lost
			$sql = "select user_id,username,role_id,r.name as role_name from users as u 
			        INNER JOIN users_roles as ur ON ur.user_id=u.id 
					INNER JOIN roles as r ON r.id=ur.role_id
					WHERE username='$username'";
			$r = pg_query($sql);
				$arr = array();
				while ($d = pg_fetch_object($r)) {
					$arr[] = strtolower($d->role_name);
				}
				$_SESSION['user_roles'] = $arr;

?>
